package com.yjq.blog.article.service.impl;

import com.yjq.blog.article.dao.ArticleTypeDao;
import com.yjq.blog.article.dto.ArticleTypeListDTO;
import com.yjq.blog.article.entity.ArticleType;
import com.yjq.blog.article.service.ArticleTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ArticleTypeServiceImpl implements ArticleTypeService {

    @Resource
    private ArticleTypeDao articleTypeDao;

    @Override
    public List<ArticleTypeListDTO> listArticleType() {

        List<ArticleType> articleTypeList = articleTypeDao.listArticleType();
        Map<Integer, List<ArticleType>> parentIdMap = articleTypeList.stream()
                .sorted(Comparator.comparing(ArticleType::getSequence))
                .collect(Collectors.groupingBy(ArticleType::getParentId));

        return typeList2DTOList(0, 1, parentIdMap);
    }

    private List<ArticleTypeListDTO> typeList2DTOList(Integer parentId, Integer level, Map<Integer, List<ArticleType>> parentIdMap) {
        List<ArticleTypeListDTO> resultList = new ArrayList<>();

        List<ArticleType> tempList = parentIdMap.get(parentId);
        if(!CollectionUtils.isEmpty(tempList)) {
            for(ArticleType articleType : tempList) {
                if(level.equals(articleType.getLevel())) {
                    ArticleTypeListDTO dto = ArticleTypeListDTO.copy(articleType);
                    dto.setChildren(typeList2DTOList(dto.getId(), dto.getLevel() + 1, parentIdMap));
                    resultList.add(dto);
                }
            }
        }
        return resultList;
    }
}
